package cn.edu.imau.zy.exam.service.impl;

import java.io.*;
import java.util.List;

import cn.edu.imau.zy.common.constant.ExaminationConstant;
import cn.edu.imau.zy.common.constant.QuestionImportParser;
import cn.edu.imau.zy.common.constant.QuestionImportParserManager;
import cn.edu.imau.zy.common.core.entity.examination.EQuestionInfo;
import cn.edu.imau.zy.common.utils.file.FileUtils;
import cn.edu.imau.zy.common.utils.file.MimeTypeUtils;
import cn.edu.imau.zy.common.utils.poi.ExcelUtil;
import cn.edu.imau.zy.exam.mapper.EQuestionInfoMapper;
import cn.edu.imau.zy.exam.service.IEQuestionInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import cn.edu.imau.zy.common.core.text.Convert;
import org.springframework.web.multipart.MultipartFile;

/**
 * 试题信息Service业务层处理
 *
 * @author gj
 * @date 2021-12-04
 */
@Service
public class EQuestionInfoServiceImpl extends ServiceImpl<EQuestionInfoMapper, EQuestionInfo> implements IEQuestionInfoService {
    @Autowired
    private EQuestionInfoMapper eQuestionInfoMapper;

    @Override
    public List<EQuestionInfo> queryList(EQuestionInfo eQuestionInfo) {
        LambdaQueryWrapper<EQuestionInfo> lqw = Wrappers.lambdaQuery();
        return this.list(lqw);
    }

    /***
     *导入试题
     * @param file
     * @return
     */
    @Override
    public boolean importQuestion(MultipartFile file) throws Exception {
        ExcelUtil<EQuestionInfo> excelUtil = new ExcelUtil<>(EQuestionInfo.class);

        List<EQuestionInfo> eQuestionInfos = null;

        InputStream inputStream = null;

        inputStream = file.getInputStream();
        eQuestionInfos = excelUtil.importExcel(inputStream);

        eQuestionInfos.forEach(info -> {
            // 拿到枚举中的 val key 和 excel 中的试题类型匹配
            for (ExaminationConstant.QuestionType type : ExaminationConstant.QuestionType.values()) {

                if (type.getName().equals(info.getQuestionTypeName())) {
                    info.setQuestionType(type.getValue());
                    break;
                }

            }

            // 进行试题解析
            QuestionImportParser excelQuestionParser = QuestionImportParserManager.build()
                    .createExcelQuestionParser(info.getQuestionType());
            info.setAnswer(excelQuestionParser.parseAnswerText(info.getAnswer()));
            info.setOptions(excelQuestionParser.parseOptionText(info.getOptions()));
        });

        return this.saveBatch(eQuestionInfos);

    }
}
